<?php

/**
 * finalClothQcWrapperForm actions.
 *
 * @package    WacStorehouse
 * @subpackage finalClothQcWrapperForm
 * @author     JianBinBi
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class finalClothQcWrapperFormActions extends WacCommonActions {
    /**
     * get searching list
     * @package
     * @author     ben
     */
    public function executeGetList(sfWebRequest $request) {

        $jqGridDataHelper = JqGridDataHelper::getInstance();

        $arrParam = array();
        if($jqGridDataHelper->loadComplexQuery($request)) {

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParam['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
//                    case "production_order_code":
//                        $arrParam['orderBy'] = "wpo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
//                        break;
//                    case "dispatch_order_code":
//                        $arrParam['orderBy'] = "wcuf.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
//                        break;
//                    case "goods_category_name":
//                        $arrParam['orderBy'] = "wgc.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
//                        break;
                    case "status_name":
                        $arrParam['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "maker_name":
                        $arrParam['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "auditor_name":
                        $arrParam['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParam['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParam, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false, $arrParam);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
    }

    /*
   * override filter list
    */
    public function filterList($listObjs) {
        $filterArr = array();
        if(count($listObjs) > 0) {
            foreach($listObjs as $listObj) {
                $tmpArr = $listObj->toArray();
                $tmpArr['production_order_code']  = $listObj->getWacDispatchOrder()->getCode();
                $tmpArr['dispatch_order_code']    = $listObj->getWacDispatchOrder()->getCode();
                $tmpArr['roll_name']              = $listObj->getRoll().$listObj->getWacRollUnitCode()->getName();
                $tmpArr['piece_length_name']      = $listObj->getPieceLength().$listObj->getWacPieceLengthUnitCode()->getName();

                $tmpArr['wrapper_name']           = $listObj->getWacWrapper()->getName();
                $tmpArr['maker_name']             = $listObj->getWacMaker()->getUsername();

                $formatDate = new DateTime($listObj->getQcDate());
                $tmpArr['qc_date']                 = $formatDate->format("Y-m-d");

                $tmpArr['status_name']             = StaticWacFormStatus::getCaptionById($listObj->getStatus());

                $filterArr[] = $tmpArr;
            }
        }

        return $filterArr;
    }

    /*
   * @return inspect result
    */
    public function inspectDataValidation(sfWebRequest $request, $params=array()) {
        $result    = JsCommonData::getSuccessDatum();
        $reqParams = $request->getParameterHolder()->getAll();


        $exceptId = isset($reqParams['id']) ? $reqParams['id'] : 0;
        if($this->mainModuleTable->isExistedCode($reqParams['code'], $exceptId)) {
            $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
            return $result;
        }

        if(empty($reqParams['dispatch_order_id']) || !Doctrine::getTable(WacTable::$dispatchOrder)->isExistedId($reqParams['dispatch_order_id'])) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_dispatch_order"),  WacErrorCode::$logicError
            );
            return $result;
        }

        return $result;
    }

    /*
   * @return list data array
    */
    public function executeAdd(sfWebRequest $request) {

        $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
        $resultSet     = JsCommonData::getCommonDatum();
        $inspectResult = $this->inspectDataValidation($request);

        if($inspectResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $inspectResult;
        }
        else {
            $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $reqParams['dispatch_order_id']);
            $targetItem      = $this->mainModuleTable->create();

            if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
                $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());

                if(isset($reqParams['code'])) {
                    $targetItem->setCode($reqParams['code']);
                }
                if(isset($reqParams['dispatch_order_id'])) {
                    $targetItem->setDispatchOrderId($reqParams['dispatch_order_id']);
                    $targetItem->setProductionOrderId($objDispatchOrder->getProductionOrderId());
                    $targetItem->setSrcProductionOrderId($objDispatchOrder->getProductionOrderId());
                }

                if(isset($reqParams['roll'])) {
                    $targetItem->setRoll($reqParams['roll']);
                }
                if(isset($reqParams['roll_unit_code'])) {
                    $targetItem->setRollUnitCode($reqParams['roll_unit_code']);
                }
                if(isset($reqParams['piece_length'])) {
                    $targetItem->setPieceLength($reqParams['piece_length']);
                }
                if(isset($reqParams['piece_length_unit_code'])) {
                    $targetItem->setPieceLengthUnitCode($reqParams['piece_length_unit_code']);
                }
                
                if(isset($reqParams['wrap_id'])) {
                    $targetItem->setWrapId($reqParams['wrap_id']);
                }
                
                if(isset($reqParams['standard'])) {
                    $targetItem->setStandard($reqParams['standard']);
                }

                if(isset($reqParams['label_requirement'])) {
                    $targetItem->setLabelRequirement($reqParams['label_requirement']);
                }

                if(isset($reqParams['level'])) {
                    $targetItem->setLevel($reqParams['level']);
                }

                if(isset($reqParams['item1'])) {
                    $targetItem->setItem1($reqParams['item1']);
                }

                if(isset($reqParams['item2'])) {
                    $targetItem->setItem2($reqParams['item2']);
                }

                if(isset($reqParams['item3'])) {
                    $targetItem->setItem3($reqParams['item3']);
                }

                if(isset($reqParams['qc_date'])) {
                    $targetItem->setQcDate($reqParams['qc_date']);
                }

                if(isset($reqParams['dispatch_date'])) {
                    $targetItem->setDispatchDate($reqParams['dispatch_date']);
                }

                if(isset($reqParams['goods_return_date'])) {
                    $targetItem->setGoodsReturnDate($reqParams['goods_return_date']);
                }

                if(isset($reqParams['memo'])) {
                    $targetItem->setMemo($reqParams['memo']);
                }

                if(isset($reqParams['label_memo'])) {
                    $targetItem->setLabelMemo($reqParams['label_memo']);
                }

                $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));
                $targetItem->save();

                $this->afterAdd($request, $targetItem);

            }

            $resultSet['items'][0] = $targetItem->toArray();
            $resultSet['info']     = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }

    /*
   * @return list data array
    */
    public function executeEdit(sfWebRequest $request) {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('id'));

        $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
        $resultSet     = JsCommonData::getCommonDatum();
        $inspectResult = $this->inspectDataValidation($request);

        if($inspectResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $inspectResult;
        }
        else {
            $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));
            $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $reqParams['dispatch_order_id']);

            if(count($reqParams)>0) {
                if(isset($reqParams['code'])) {
                    $targetItem->setCode($reqParams['code']);
                }
                if(isset($reqParams['dispatch_order_id'])) {
                    $targetItem->setDispatchOrderId($reqParams['dispatch_order_id']);
                    $targetItem->setProductionOrderId($objDispatchOrder->getProductionOrderId());
                    $targetItem->setSrcProductionOrderId($objDispatchOrder->getProductionOrderId());
                }

                if(isset($reqParams['roll'])) {
                    $targetItem->setRoll($reqParams['roll']);
                }
                if(isset($reqParams['roll_unit_code'])) {
                    $targetItem->setRollUnitCode($reqParams['roll_unit_code']);
                }
                if(isset($reqParams['piece_length'])) {
                    $targetItem->setPieceLength($reqParams['piece_length']);
                }
                if(isset($reqParams['piece_length_unit_code'])) {
                    $targetItem->setPieceLengthUnitCode($reqParams['piece_length_unit_code']);
                }

                if(isset($reqParams['wrap_id'])) {
                    $targetItem->setWrapId($reqParams['wrap_id']);
                }

                if(isset($reqParams['standard'])) {
                    $targetItem->setStandard($reqParams['standard']);
                }

                if(isset($reqParams['label_requirement'])) {
                    $targetItem->setLabelRequirement($reqParams['label_requirement']);
                }

                if(isset($reqParams['level'])) {
                    $targetItem->setLevel($reqParams['level']);
                }

                if(isset($reqParams['item1'])) {
                    $targetItem->setItem1($reqParams['item1']);
                }

                if(isset($reqParams['item2'])) {
                    $targetItem->setItem2($reqParams['item2']);
                }

                if(isset($reqParams['item3'])) {
                    $targetItem->setItem3($reqParams['item3']);
                }

                if(isset($reqParams['qc_date'])) {
                    $targetItem->setQcDate($reqParams['qc_date']);
                }

                if(isset($reqParams['dispatch_date'])) {
                    $targetItem->setDispatchDate($reqParams['dispatch_date']);
                }

                if(isset($reqParams['goods_return_date'])) {
                    $targetItem->setGoodsReturnDate($reqParams['goods_return_date']);
                }

                if(isset($reqParams['memo'])) {
                    $targetItem->setMemo($reqParams['memo']);
                }

                if(isset($reqParams['label_memo'])) {
                    $targetItem->setLabelMemo($reqParams['label_memo']);
                }

                $targetItem->save();

                $this->afterEdit($request, $targetItem);
            }

            $resultSet['items'][0] = $targetItem->toArray();
            $resultSet['info']     = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }

    /*
   * @return inspect result
    */
    protected function auditValidation(sfWebRequest $request, $objForm, $params=array()) {
        $result    = JsCommonData::getSuccessDatum();
        $reqParams = $request->getParameterHolder()->getAll();

        if($objForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
            );
            return $result;
        }

        return $result;
    }

    /*
   * @return list data array
    */
    public function executeGetFormData(sfWebRequest $request) {
        $resultSet = JsCommonData::getCommonDatum();
        $resultSet['info'] = JsCommonData::getSuccessDatum();

        $resultSet['items']['unit'] = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();
        $resultSet['items']['wrapper'] = Doctrine::getTable(WacTable::$wrapper)->getIdNameHash();

        $resultSet['items']['default']['piece_length_unit_code'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$checkLengthUnitCode);
        $resultSet['items']['default']['roll_unit_code'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$rollUnitCode);


        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }

    /*
     * @return list data array
    */
    public function executeAudit(sfWebRequest $request) {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('final_cloth_qc_wrapper_form_id'));

        $resultSet = JsCommonData::getCommonDatum();

        $objForm = Doctrine::getTable(WacTable::$finalClothQcWrapperForm)->findOneBy('id', $request->getParameter('final_cloth_qc_wrapper_form_id'));
        if($objForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
            $resultSet['info'] = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
            );
        }

        $objForm = Doctrine::getTable(WacTable::$finalClothQcWrapperForm)->findOneBy('id', $request->getParameter('final_cloth_qc_wrapper_form_id'));
        $validationResult = $this->auditValidation($request, $objForm);

        if($validationResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $validationResult;
        }
        else {
            $objForm->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
            $objForm->setAuditorId($this->getUser()->getGuardUser()->getId());
            $objForm->setAuditorDate(format_date(time()));
            $objForm->save();

            $resultSet['info'] = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }
}
